package com.wenhao.future;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @author Wenhao Tong
 * @create 2021-08-20 18:52
 */
public class Demo1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("1111");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 因为是异步的所以hello会先输出
        System.out.println("hello");
        completableFuture.get();
    }

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    @Test
    public void test1 () throws ExecutionException, InterruptedException {
        // 一些按顺序执行
        CompletableFuture<Void> task_1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " task_1 start...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },executor).whenComplete((x,u) -> {
            System.out.println("task_1 complete");
        });

        CompletableFuture<Void> task_2 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " task_2 start...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },executor).whenComplete((x,u) -> {
            System.out.println("task_2 complete");
        });
        System.out.println("hello");
        CompletableFuture<Void> task_3 = CompletableFuture.allOf(task_1,task_2);
        CompletableFuture<Object> task_4 = CompletableFuture.anyOf(task_1,task_2);
//        System.out.println(task_3.get() + "task_3");
        System.out.println(task_4.get() + "task_4");
    }
}
